#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>
using namespace std;

struct ThreadInfo
{
    pthread_t tid;
    string name;
};

static const int defaultcap = 10;

template<class T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }

    string GetThreadName(pthread_t tid)
    {
        for(auto& thread : _threads)
        {
            if(thread.tid == tid)
                return thread.name;
        }
        return "None";
    }

public:
    static void* HandlerTask(void* args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        string name = tp->GetThreadName(pthread_self());
        while(true)
        {
            tp->Lock();
            while(tp->IsQueueEmpty())
            {
                tp->ThreadSleep();
            }
            T task = tp->Pop();
            tp->Unlock();

            task();
            cout << name << " run, " << "result: " << task.GetResult() << endl;
        }
    }

    void Start()
    {
        int num = _threads.size();
        for(int i = 0; i < num; i++)
        {
            _threads[i].name = "thread-" + to_string(i);
            pthread_create(&(_threads[i].tid), nullptr, HandlerTask, this);
        }
    }

    void Push(const T& in)
    {
        Lock();
        _tasks.push(in);
        ThreadWakeup();
        Unlock();
    }

    T Pop()
    {
        T out = _tasks.front();
        _tasks.pop();
        return out;
    }

    static ThreadPool<T>* GetInstance()
    {
        if(_tp == nullptr)
        {
            pthread_mutex_lock(&_lock);
            if(_tp == nullptr)
            {
                cout << "log: singleton create done first!" << endl;
                _tp = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_lock);
        }
        return _tp;
    }

private:
    ThreadPool(int cap = defaultcap)
        : _threads(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ThreadPool(const ThreadPool<T>&) = delete;
    ThreadPool<T>& operator=(const ThreadPool<T>&) = delete;

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    vector<ThreadInfo> _threads;
    queue<T> _tasks;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T>* _tp;
    static pthread_mutex_t _lock;
};

template<class T>
ThreadPool<T>* ThreadPool<T>::_tp = nullptr;

template<class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;